package com.wei.test.config;

import com.wei.test.Service.LogService;
import com.wei.test.Util.AppUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
    private static String prefix = "\n\t\t\t";

    @Autowired
    LogService logService;

    @Autowired
    AppUtil appUtil;

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Map exceptionHandler(HttpServletRequest request, Exception exception) throws IOException {
        String parameter = appUtil.getRequestBody(request);
        StackTraceElement[] traceElements = exception.getStackTrace();
        String error = "url: " + request.getRequestURL().toString() + ", ip: " + appUtil.getRemoteHost(request) + prefix;

        if ("POST".equalsIgnoreCase(request.getMethod())) {
            error += "parameters: " + parameter + prefix;
        }

        for (int i = 0; i < traceElements.length; i++) {
            error += traceElements[i].toString() + prefix;
            if (i == 3)
                break;
        }

        logService.error(error);
        return appUtil.getResult(-1);
    }
}
